package com.shux.redis.biz.impl;

import java.util.Collection;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import com.alibaba.dubbo.config.annotation.Service;
import com.shux.redis.biz.IRedisBiz;
import com.shux.redis.dao.IRedisDao;
import com.shux.utils.other.SysConfigUtil;
import com.shux.utils.string.StringUtil;

/**
 **********************************************
 *  描述：
 * Simba.Hua
 * 2017年8月3日
 **********************************************
**/
@Component
@Service(/*interfaceName="com.shux.redis.biz.IRedisBiz",protocol = {"dubbo"}*/)
public class RedisBizImpl<T> implements IRedisBiz<T>{
    private Logger logger = LoggerFactory.getLogger(getClass());
    private static final Integer TIMEOUT_DEFAULT = 2000;
    @Resource(name = "redisDao")
    private IRedisDao<T> redisDao;
    
    /**
     * 新增数据
     * @param key
     * @param value
     */
    public void set(Object key,T value,Integer timeout){
        if (null == value) {
            return;
        }
        if (value instanceof String) {
            if(StringUtil.isEmpty(value.toString())){
                return;
            }
        }
        if(timeout == null){
            timeout = SysConfigUtil.get("timeout") == null?TIMEOUT_DEFAULT:Integer.valueOf((String)SysConfigUtil.get("timeout")); 
        }
        
        redisDao.set(key, value,timeout);
    }
    public void set(Object key,T value){
        set(key,value,null);
    }
    /**
     * 获取值
     * @param key
     * @return
     */
    @SuppressWarnings("unchecked")
    public T get(Object key){
        return (T) redisDao.get(key);
    }
    /**
     * 删除为key的值
     * @param key
     */
    public void delete(String key){
        logger.info(StringUtil.join("delete the key ",key," from redis!"));
        redisDao.delete(key);
    }
    /**
     * 
     * @param keys
     */
    public void deleteBatch(Collection<String> keys){
        redisDao.deleteBatch(keys);
    }
    
    public  List<T> getBatch(Collection<Object> keys){
        
        return  getOpsForValue().multiGet(keys);
    }
    
    public T getAndSet(Object key,T value){
        return getOpsForValue().getAndSet(key, value);
    }
    
    public ValueOperations<Object, T> getOpsForValue(){
        return getRedisClusterTemplate().opsForValue();
    }
    @Override
    public RedisTemplate<Object, T> getRedisClusterTemplate() {
        // TODO Auto-generated method stub
        return redisDao.getRedisClusterTemplate();
    }
    
}
